#!/usr/bin/env python
import random
import sqlite3
import sys
import time,datetime
import threading
from kisp import *
from actions import *

db_file = 'invigilator.db'


class TriggerThread(threading.Thread):
	def __init__(self, id,event_id,action,arguments):
		threading.Thread.__init__(self)
		self.id = id
		self.event_id = event_id
		self.action = action
		self.arguments = arguments
		self.info = {}
	
	def run(self):
		db = sqlite3.connect(db_file,isolation_level=None)
		sql = db.cursor()
		
		result = sql.execute("select events.status from events where events.id=?",[self.event_id] ).fetchone()
		if not result or result[0] != "NEW":
			sql.execute('DELETE FROM trigger_schedule WHERE EVENT_ID=?',[self.event_id])
			sql.close
			return
	
		result = sql.execute("select trigger_schedule.id, trigger_schedule.event_id, tag_descriptions.id, tag_descriptions.title, tag_descriptions.description, polls.title, events.time from polls, tag_descriptions, events, trigger_schedule where tag_descriptions.id = events.tag_id and polls.id = events.poll_id and trigger_schedule.event_id = events.id and trigger_schedule.id=? and trigger_schedule.event_id=?",(self.id , self.event_id) ).fetchone()

		if result: 
			self.info = { 'trigger.id': result[0], 'event.id': result[1], 'tag.id':result[2], 'tag.title':result[3], 'tag.description':result[4], 'poll.title':result[5], 'event.time':result[6]}

		sql.execute('DELETE FROM trigger_schedule WHERE ID=? AND EVENT_ID=?',(self.id,self.event_id))
		for action in KISP.plugins:
			if action.Name == self.action and action.Type == "Action":
				result=action().Start(self.info,self.arguments)
				if result != 0:
					sql.execute('INSERT INTO trigger_schedule (ID, EVENT_ID, TIME) VALUES ( ?, ?, ? )',  (self.id,self.event_id,datetime.datetime.now()))
				sql.close
				break

def main():	
	db = sqlite3.connect(db_file,isolation_level=None)
   	sql = db.cursor()
	sql.execute("create table IF NOT EXISTS rrdb (TIME TIMESTAMP , POLL_ID text, STATE real, VALUE real, DESCRIPTION text)")
   	sql.execute("create table IF NOT EXISTS polls(ID text, TITLE text, MINUTES real, sensor text, ARGUMENTS text, STATE real)")
	sql.execute("create table IF NOT EXISTS poll_schedule(POLL_ID text, TIME TIMESTAMP)")
	sql.execute("create table IF NOT EXISTS tags(ID text, POLL_ID text)")
	sql.execute("create table IF NOT EXISTS tag_descriptions(ID text, TITLE text, DESCRIPTION text)")
	sql.execute("create table IF NOT EXISTS events(ID text, TAG_ID text, POLL_ID text, TIME TIMESTAMP, STATUS text)")
	sql.execute("create table IF NOT EXISTS triggers(ID text, TAG_ID text, DESCRIPTION text, ACTION text, ARGUMENTS text, TIMING real)")	
	sql.execute("create table IF NOT EXISTS trigger_schedule(ID text, EVENT_ID text, TIME TIMESTAMP)")
		
	sql.execute("select TRIGGERS.ID, TRIGGER_SCHEDULE.EVENT_ID, TRIGGERS.action, TRIGGERS.ARGUMENTS from TRIGGERS, TRIGGER_SCHEDULE WHERE TRIGGERS.ID = TRIGGER_SCHEDULE.ID AND TRIGGER_SCHEDULE.TIME < ?",[datetime.datetime.now()])
	for row in sql:
		TriggerThread(row[0],row[1],row[2],row[3]).start()

	sql.close

if __name__ == "__main__":
	main()
